package com.naodong.shenluntiku.mvp.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.naodong.shenluntiku.R;
import com.naodong.shenluntiku.di.component.DaggerFindComponent;
import com.naodong.shenluntiku.di.module.BannerModule;
import com.naodong.shenluntiku.di.module.FindModule;
import com.naodong.shenluntiku.mvp.contract.BannerContract;
import com.naodong.shenluntiku.mvp.contract.FindContract;
import com.naodong.shenluntiku.mvp.model.bean.Banner;
import com.naodong.shenluntiku.mvp.model.bean.EventBusTag;
import com.naodong.shenluntiku.mvp.model.bean.GradeChartData;
import com.naodong.shenluntiku.mvp.model.bean.OnceTipType;
import com.naodong.shenluntiku.mvp.model.bean.SubjectType;
import com.naodong.shenluntiku.mvp.model.data.manager.BoxManager;
import com.naodong.shenluntiku.mvp.presenter.BannerPresenter;
import com.naodong.shenluntiku.mvp.presenter.FindPresenter;
import com.naodong.shenluntiku.mvp.view.activity.AssessmentActivity;
import com.naodong.shenluntiku.mvp.view.activity.AssessmentActivityAutoBundle;
import com.naodong.shenluntiku.mvp.view.activity.FeedbackActivity;
import com.naodong.shenluntiku.mvp.view.activity.SubjectAnalysisListActivityAutoBundle;
import com.naodong.shenluntiku.mvp.view.activity.VideoAnalysisListActivity;
import com.naodong.shenluntiku.mvp.view.activity.WebViewActivityAutoBundle;
import com.naodong.shenluntiku.mvp.view.widget.LineChartView;
import com.naodong.shenluntiku.util.ImageLoaderUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.github.douglasjunior.androidSimpleTooltip.ArrowDrawable;
import io.github.douglasjunior.androidSimpleTooltip.SimpleTooltip;
import me.shingohu.man.base.BaseMVPFragment;
import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.model.bean.SimpleEvent;
import me.shingohu.man.util.UiUtils;
import me.shingohu.man.widget.BannerLayout;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by hujie on 17/4/18.
 */

public class FindFragment extends BaseMVPFragment<FindPresenter> implements FindContract.View, BannerContract.View, SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(value = R.id.banner)
    BannerLayout bannerLayout;


    @BindView(R.id.gradeTV)
    TextView gradeTV;


    @BindView(R.id.gradeListView)
    LinearLayout gradeListView;//练习成绩

    @BindView(R.id.gradeChartView)
    View gradeChartView;//成绩图表

    @BindView(R.id.gradeView)
    View gradeView;

    @BindView(R.id.lineChartView)
    LineChartView lineChartView;

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    LayoutInflater layoutInflater;


    @BindView(R.id.analysisView)
    View analysisView;

    int mode = 1; //成绩显示模式 1表示列表 2表示图表


    @Inject
    BannerPresenter bannerPresenter;


    public static SupportFragment getInstance() {
        return new FindFragment();
    }


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerFindComponent.builder()
                .appComponent(appComponent)
                .findModule(new FindModule(this)) //请将LoginModule()第一个首字母改为小写
                .bannerModule(new BannerModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onViewCreated(Bundle savedInstanceState) {

        swipeRefreshLayout.setOnRefreshListener(this);
        initBanner();
    }

    @OnClick(R.id.gradeHeadView)
    public void onGradeHeadViewClick() {
        mode = mode == 1 ? 2 : 1;
        setGradeHeadMode(mode);
    }

    private void setGradeHeadMode(int mode) {
        if (mode == 1) {
            gradeTV.setText("练习成绩");
            gradeChartView.setVisibility(View.INVISIBLE);
            gradeListView.setVisibility(View.VISIBLE);
        } else {
            gradeTV.setText("成绩统计");
            gradeChartView.setVisibility(View.VISIBLE);
            gradeListView.setVisibility(View.INVISIBLE);
            //加载选中的题型成绩数据
            mPresenter.getGradeChartData((Integer) tabLayout.getTabAt(tabLayout.getSelectedTabPosition()).getTag());
        }
    }


    private void initBanner() {
        layoutInflater = LayoutInflater.from(_mActivity);

        bannerLayout.setImageLoader((BannerLayout.ImageLoader) (context, s, imageView) -> {
            imageView.setBackgroundResource(R.drawable.kedou_placeholder);
            ImageLoaderUtil.loadImage(mActivity, s, imageView);
        });
        bannerLayout.setOnBannerItemClickListener(position -> {
            if (bannerLayout.getBanners() != null) {
                Banner banner = (Banner) bannerLayout.getBanners().get(position);
                if (banner.getResourceType() == 1) {
                    //h5
                    startActivity(WebViewActivityAutoBundle.builder(banner.getResourceValue()).title(banner.getTitle()).build(mActivity));
                } else if (banner.getResourceType() == 10) {
                    //跳转到界面
                    if ("feedback".equals(banner.getResourceValue())) {
                        Intent intent = new Intent(mActivity, FeedbackActivity.class);
                        startActivity(intent);
                    }
                }
            }
        });

    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        mPresenter.getFindSubjectItems(false);
        bannerPresenter.getBanner();
    }


    /**
     * 显示成绩的列表
     */
    public void setGradeSubjectItemsView(List<SubjectType> subjectItems) {

        int progressbarWidth = UiUtils.getScreenWidth() - UiUtils.dip2px(90);
        gradeListView.removeAllViews();
        for (SubjectType subjectItem : subjectItems) {
            View subjectItemView = layoutInflater.inflate(R.layout.item_subject_grade, null);
            TextView nameTV = (TextView) subjectItemView.findViewById(R.id.nameTV);

            TextView finishCountTV = (TextView) subjectItemView.findViewById(R.id.finishCountTV);
            ProgressBar progressBar = (ProgressBar) subjectItemView.findViewById(R.id.progressBar);

            View lineView = subjectItemView.findViewById(R.id.lineView);
            View avgView = subjectItemView.findViewById(R.id.avgView);

            View curView = subjectItemView.findViewById(R.id.curView);

            if (subjectItems.indexOf(subjectItem) == subjectItems.size() - 1) {
                lineView.setVisibility(View.INVISIBLE);
            }
            nameTV.setText(subjectItem.getName());

            finishCountTV.setText("已做" + subjectItem.getChoiceUserFinish() + "题");
            progressBar.setProgress(subjectItem.getChoiceUserAvgCorrectRate());
            gradeListView.addView(subjectItemView);

            subjectItemView.findViewById(R.id.doBtn).setOnClickListener(v -> {
                startActivity(AssessmentActivityAutoBundle.builder(subjectItem.getName(), subjectItem.getSubTypeId(), AssessmentActivity.FROM_FIND).build(getActivity()));
            });


            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) avgView.getLayoutParams();
            int width = progressbarWidth;
            int avgViewLocation = width * subjectItem.getChoiceAvgCorrectRate() / 100;
            if (avgViewLocation + avgView.getWidth() > width) {
                avgViewLocation = width - avgView.getWidth();
            }
            lp.leftMargin = avgViewLocation;
            avgView.setLayoutParams(lp);

            FrameLayout.LayoutParams lp1 = (FrameLayout.LayoutParams) curView.getLayoutParams();
            lp1.leftMargin = progressbarWidth * subjectItem.getChoiceUserAvgCorrectRate() / 100;
            curView.setLayoutParams(lp1);

            subjectItemView.setOnClickListener(v -> {
                showTipView(subjectItem, curView, avgView);
            });

        }

        //第一次进来时展示小气泡
        if (!BoxManager.getInstance().queryBoxOnceStatusByType(OnceTipType.find_value_tip)) {
            BoxManager.getInstance().putBoxOnce(OnceTipType.find_value_tip, true);
            gradeListView.getChildAt(0).performClick();
        }


    }

    private void showTipView(SubjectType subjectType, View curView, View avgView) {
        new SimpleTooltip.Builder(mActivity).anchorView(avgView)
                .text("  平台平均值:" + subjectType.getChoiceAvgCorrectRate() + "%  ")
                .gravity(Gravity.BOTTOM)
                .padding(UiUtils.dip2px(4) + 0.0f)
                .backgroundColor(getResources().getColor(R.color.color4FAEFF))
                .arrowColor(getResources().getColor(R.color.color4FAEFF))
                .contentView(R.layout.grade_avg_tip_layout)
                .arrowWidth(UiUtils.dip2px(8))
                .arrowHeight(UiUtils.dip2px(8))
                .modal(false)
                .arrowDirection(ArrowDrawable.TOP)

                .build().show();

        new SimpleTooltip.Builder(mActivity).anchorView(curView)
                .text("  正确率:" + subjectType.getChoiceUserAvgCorrectRate() + "%  ")
                .gravity(Gravity.TOP)
                .padding(UiUtils.dip2px(4) + 0.0f)
                .backgroundColor(getResources().getColor(R.color.color4FAEFF))
                .arrowColor(getResources().getColor(R.color.color4FAEFF))
                .contentView(R.layout.grade_avg_tip_layout)
                .arrowWidth(UiUtils.dip2px(8))
                .arrowHeight(UiUtils.dip2px(8))
                .modal(false)
                .arrowDirection(ArrowDrawable.BOTTOM)
                .build().show();
    }


    /**
     * 设置成绩图表的头部
     *
     * @param subjectItems
     */
    private void setGradeChartHeadView(List<SubjectType> subjectItems) {
        tabLayout.removeAllTabs();
        tabLayout.clearOnTabSelectedListeners();
        for (SubjectType subjectItem : subjectItems) {
            TabLayout.Tab tabItem = tabLayout.newTab();
            tabItem.setTag(subjectItem.getSubTypeId());
            tabItem.setText(subjectItem.getName());
            tabLayout.addTab(tabItem);
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (mode == 2) {
                    mPresenter.getGradeChartData((Integer) tab.getTag());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }


    @OnClick(value = R.id.seeAnalysis)
    public void onModelArticleClick() {
        if (mPresenter.getSubjectTypes() != null) {
            startActivity(SubjectAnalysisListActivityAutoBundle.builder(mPresenter.getSubjectTypes()).build(getContext()));
        }
    }

    @OnClick(value = R.id.listenAnalysis)
    public void onListenAnalysisClick() {
        Intent intent = new Intent(_mActivity, VideoAnalysisListActivity.class);
        startActivity(intent);
    }

    @Override
    protected int layoutId() {
        return R.layout.f_find;
    }

    @Override
    public void showMessage(String msg) {

    }


    @Override
    public void showFindSubjectItem(List<SubjectType> subjectItems) {
        resetData();
        analysisView.setVisibility(View.VISIBLE);
        setGradeSubjectItemsView(subjectItems);
        setGradeChartHeadView(subjectItems);
    }

    private void resetData() {
        mode = 1;
        setGradeHeadMode(mode);
        gradeView.setVisibility(View.VISIBLE);
    }

    @Override
    public void showGradeChartData(GradeChartData gradeChartData) {
        lineChartView.resetValue();
        List<GradeChartData.Part> parts = gradeChartData.getParts();
        if (parts != null && parts.size() > 0) {
            //折线对应的数据
            Map<String, Integer> value = new HashMap<>();
            List<String> xValue = new ArrayList<>();

            for (GradeChartData.Part part : parts) {
                xValue.add(part.getPartFinishNum() + "");
                value.put(part.getPartFinishNum() + "", part.getPartCorrectRate());
            }
            lineChartView.setValue(value, xValue);
            lineChartView.setSelectIndex(xValue.size());
            lineChartView.scrollToTargetIndex(xValue.size());
        }

    }

    @Override
    public void onRefreshBegin() {
        swipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void onRefreshFinish() {
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void showGradeNoData() {
        lineChartView.resetValue();
    }

    @Override
    public void onRequesrStart() {
        progressHudUtil.showProgressHud();
    }

    @Override
    public void onRequestFinish() {
        progressHudUtil.dismissProgressHud();
    }

    @Override
    public void onRefresh() {
        mPresenter.refreshData();
        bannerPresenter.getBanner();
    }

    @Override
    public void showBanner(List<Banner> banners) {
        bannerLayout.loadViewUrls(banners);
        bannerLayout.getPager().setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    swipeRefreshLayout.setEnabled(false);
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    swipeRefreshLayout.setEnabled(true);
                    break;
            }
            return false;
        });
    }

    @Override
    protected boolean userEventBus() {
        return true;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SimpleEvent event) {
        if (event.getType() == EventBusTag.NOTIFY_FINDFRAGMENT_REFRESH) {
            if (mPresenter != null) {
                mPresenter.refreshData();
            }
        }
    }
}
